package com.stack.knowyouservice.service.impl;

import com.stack.knowyoubase.anotional.TimeOut;
import com.stack.knowyoubean.bean.Answer;
import com.stack.knowyoubean.bean.HomeWork;
import com.stack.knowyoubase.constant.GlobalConst;
import com.stack.knowyoudao.dao.AnswerDao;
import com.stack.knowyoudao.dao.HomeWorkDao;
import com.stack.knowyouservice.service.AnswerService;
import com.stack.knowyoubase.util.PageUtil;
import com.stack.knowyoubase.util.PreHomeWorkUtil;
import com.stack.knowyoubase.util.TimeUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * 学生答案表服务层
 *
 * @author stack
 */
@Service
@Scope("singleton")

public class AnswerServiceImpl implements AnswerService {

    @Resource
    private AnswerDao answerDao;
    @Resource
    private HomeWorkDao homeWorkDao;
    @Resource
    private PageUtil pageUtil;
    @Resource
    private PreHomeWorkUtil preHomeWorkUtil;
    @Resource
    private TimeUtil timeUtil;

    /**
     * 学生作答信息
     *
     * @param hid   作业号
     * @param stuid 学号
     * @param sid   课程号
     * @return 学生作答实体
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    @TimeOut
    @Override
    public Answer answerInfo(Integer hid, Integer stuid, Integer sid) {
        List<Integer> homeWorkBySid = homeWorkDao.findHomeWorkBySid(sid);
        boolean contains = homeWorkBySid.contains(hid);
        if (!contains) {
            return null;
        } else {
            HomeWork homeWorkById = homeWorkDao.findHomeWorkById(hid);
            Answer answer = answerDao.findAnswerByHid(hid, stuid);
            if (answer == null) {
                answer = new Answer();
                answer.setHid(hid);
                answer.setStuid(stuid);
                answerDao.insertAnswer(answer);
            }
            //补全作业信息

            if (homeWorkById.getHkid().equals(GlobalConst.HOMEWORK_PRE)) {
                //匹配预习作业
                if (StringUtils.isEmpty(answer.getContent())) {
                    answer.setPreModel(preHomeWorkUtil.modelCreate(homeWorkById.getHcontent()));
                } else {
                    answer.setPreModel(preHomeWorkUtil.modelCreate(answer.getContent()));
                }
            }

            answer.setHcontent(homeWorkById.getHcontent());
            answer.setHstatus(homeWorkById.getHstatus());
            answer.setHtime(homeWorkById.getHtime());
            answer.setSid(homeWorkById.getSid());
            if (homeWorkById.getHstatus() == GlobalConst.HSTATUS_END) {
                answer.setHanswer(homeWorkById.getHanswer());
            }
            return answer;
        }
    }

    /**
     * 作业更新
     *
     * @param answer         作业答案实体
     * @param authentication 权限信息
     * @return 更新标记
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    @TimeOut
    @Override
    public HashMap<String, Object> answerUpdate(Answer answer, Authentication authentication) {
        HashMap<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("flag", false);
        resultMap.put("msg", "提交失败");
        //鉴定学号是否为空和作业号用于权限检验为空出异常
        if (answer.getStuid() == null) {
            return resultMap;
        }
        if (answer.getHid() == null) {
            return resultMap;
        }

        //获取认证角色信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        String role = "";
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();
        }
        if (GlobalConst.TEACHER_ROLE.equals(role)) {
            //判断是否持有该作业权限,注意教师这个值的设置
            List<Integer> homeWorkBySid = homeWorkDao.findHomeWorkBySid(answer.getSid());
            boolean contains = homeWorkBySid.contains(answer.getHid());
            if (!contains) {
                return resultMap;
            }
            //利用查询进行鉴权和补齐字段
            Answer answerByHid = answerDao.findAnswerByHid(answer.getHid(), answer.getStuid());
            if (answerByHid == null) {
                return resultMap;
            } else {
                answerByHid.setComment(answer.getComment());
                answerByHid.setScore(answer.getScore());
                int i = answerDao.updateAnswer(answerByHid);
                if (i == 1) {
                    resultMap.put("flag", true);
                    resultMap.put("msg", "提交成功");
                    return resultMap;
                } else {
                    return resultMap;
                }
            }

        }
        if (GlobalConst.STUDENT_ROLE.equals(role)) {
            //防止注入鉴定账号
            if (answer.getStuid() != Integer.parseInt(authentication.getName())) {
                return resultMap;
            }
            //经过查询补齐字段
            Answer answerByHid = answerDao.findAnswerByHid(answer.getHid(), Integer.parseInt(authentication.getName()));
            if (answerByHid == null) {
                return resultMap;
            } else {
                //提交答案与截止时间检测
                boolean effectiveDate = timeUtil.isEffectiveDate(answerByHid.getHtime());
                if (effectiveDate == false) {
                    resultMap.put("msg", "提交失败，作业超时");
                    return resultMap;
                }
                answerByHid.setContent(answer.getContent());
                int i = answerDao.updateAnswer(answerByHid);
                if (i == 1) {
                    resultMap.put("flag", true);
                    resultMap.put("msg", "提交成功");
                    return resultMap;
                } else {
                    return resultMap;
                }
            }
        }
        return resultMap;
    }

    /**
     * 学生作答列表（教师）
     *
     * @param hid     作业号
     * @param stuname 学生姓名
     * @param score   成绩
     * @param stuid   学号
     * @param page    页码
     * @param limit   条数
     * @return 学生作答列表
     */
    @Transactional(readOnly = true, rollbackFor = Throwable.class)
    @TimeOut
    @Override
    public HashMap<String, Object> answerList(Integer hid, String stuname, Integer score, Integer stuid, Integer page, Integer limit) {
        HashMap<String, Integer> pageMap = pageUtil.pageCreate(page, limit);
        //stuname检验在前
        if (!StringUtils.isEmpty(stuname)) {
            stuname = "%" + stuname + "%";
        }
        //数量查询
        Integer count = answerDao.findAnswerCount(hid, stuid, score, stuname);
        HashMap<String, Object> homeworkMap = new HashMap<>(2);
        if (count == 0) {
            homeworkMap.put("count", count);
            homeworkMap.put("answerList", null);
        } else {
            List<Answer> answer = answerDao.findAnswer(hid, stuid, score, stuname, pageMap.get("page"), pageMap.get("limit"));
            homeworkMap.put("count", count);
            homeworkMap.put("answerList", answer);
        }
        return homeworkMap;
    }


}
